#! /usr/bin/env python3
# encoding: utf-8
"""
@file: common.py
@author: www.xcooo.cn
@Mail: 602006050@qq.com
"""
import functools
# 公用的自定义工具类
from flask import current_app
from flask import g
from flask import session

from info.models import User


def to_index_cls(index):
    '''返回指定索引的类型'''
    if index == 0:
        return 'first'
    elif index == 1:
        return 'second'
    elif index == 2:
        return  'third'
    else:
        return ''

# 自定义装饰器
def user_login_data(f):
    # 使用functools.wraps 装饰内层函数,可以保持当前函数装饰的函数的名字__name__不变
    @functools.wraps(f)
    def wrpper(*args,**kwargs):
        user_id = session.get('user_id', None)
        user = None
        # 查找用户id对应的用户模型
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        # 把查询出来的数据赋值给g变量
        g.user = user

        return f(*args,**kwargs)
    return wrpper

# 用户的信息抽取
# def query_user_info():
#     # 显示用户登陆的逻辑
#     # 获取用户id
#     user_id = session.get('user_id', None)
#     user = None
#     # 查找用户id对应的用户模型
#     if user_id:
#         try:
#             user = User.query.get(user_id)
#         except Exception as e:
#             current_app.logger.error(e)
#         return user
#     return None
